<!--
 * @description  : 证件-许可证延续通知书
 * @descriptionDetail: 证件-许可证延续通知书
 * @copyright    : 浙江烟草
 * @author       : sy
 * @create       : 2022-08-25 15:29:13
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :isWhite="true" backText="返回" title="许可证延续通知书"></theme-navbar>
    <!-- #endif -->
    
    <view class="content">
      <u-form :label-style="labelStyle" :error-type="errorType" label-position="top" :rules="rules" :model="docContinue" ref="uForm">
        <u-form-item label="当事人" :required="isRequired" prop="acceptPerson" :label-width="labelWidth">
          <u-input placeholder="请填写当事人" :disabled="!canEdit" v-model="docContinue.acceptPerson" />
        </u-form-item>
        <u-form-item
          :label-width="labelWidth" 
          :required="isRequired"
          label="许可证截止日期"
          right-icon="arrow-right"
          prop="validateEnd"
          ref="startChangeRef"
        >
          <u-input placeholder="请输入时间" :disabled="true" v-model="docContinue.validateEnd" @click="clicDatekHandle('isShowCyBegin')" />
        </u-form-item>
        <u-form-item>
          <view class="person-info">
            <view class="p-title">
              <view class="doc-sub-required">
                *
              </view>
              <view class="doc-sub-title">
                承办人(请选择2人)
              </view>
              <view class="uicon-sty" :style="!canEdit?'pointer-events: none;':''" @click="addTakerUser('docContinue')">
                <u-icon name="plus-circle" :color="$theme.u_type_primary" size="40"></u-icon>
              </view>
            </view>  
            <view class="p-content" v-for="(item,index) in employeeList" :key="index">
              <text class="p-width">
                {{ item.personName }}
              </text>
              <text>
                {{ item.leCertNo }}
              </text>
            </view>
          </view>
        </u-form-item>
        <u-form-item
          :required="isRequired"
          :label-width="labelWidth" 
          label="承办日期"
          right-icon="arrow-right"
          prop="docDate"
          ref="endChangeRef"
        >
          <u-input placeholder="请输入时间" :disabled="true" v-model="docContinue.docDate" @click="clicDatekHandle('isShowCyEnd')" />
        </u-form-item>
        <u-form-item :label-position="labelPosition" style="padding:0px;">
          <view class="desc-btm">
            本文书一式二份，一份送达持证人，一份存档
          </view>
        </u-form-item>
      </u-form>
      <view class="gap-space"></view>
    </view>
    <u-calendar :mode="mode" :max-date="maxDate" v-model="isShowCyBegin" @change="changeDate('validateEnd',$event)">
    </u-calendar>
    <u-calendar :mode="mode" :max-date="maxDate" v-model="isShowCyEnd" @change="changeDate('docDate',$event)">
    </u-calendar>
    <!-- 承办人 -->
    <u-popup mode="bottom" border-radius="14" height="80%" v-model="personShow">
      <multi-select :options="personOptions" @select="handlerSelectPersons"></multi-select>
    </u-popup>
    <!-- 底部按钮开始 -->
    <view class="submit-btns btn-other-cls">
      <u-button plain type="primary" class="u-btn" v-if="canEdit" @click="submitAudit('save')">
        保存
      </u-button>
      <u-button type="primary" class="u-btn" v-if="!canEdit" @click="downloadFile">
        打印
      </u-button>
      <u-button type="primary" class="u-btn" v-if="canEdit" @click="submitAudit('submit')">
        提交
      </u-button>
    </view>
  </view>
</template>

<script> 
import {dateUtils,} from "@/common/util";
import multiSelect from '@/components/multi-select.vue';
import certificateService from "@/service/certificate/certificate.service.js";
import util from "@/common/util.js";
import commonService from "@/service/common/common.service";
import {LOG_STATUS,LOG_OP_TYPE,} from '@/service/common/mapping/enum.js';
import checkService from "@/service/check/check.service";
export default {
  components: { 
    multiSelect,
  },
  props: {
    
  },
  data() {
    return {
      labelPosition:'top',
      labelStyle: {
        fontWeight: 400,
        color: this.$theme.u_main_color,
      },
      rightIconStyle: {
        'fontSize': '40rpx',
        'color': this.$theme.u_type_primary,
      },
      labelWidth:'360',
      mode: 'date',
      maxDate: this.$u.timeFormat(Date.now()),
      errorType: ['border-bottom','message',],
      isShowCyBegin: false,
      isShowCyEnd: false,
      isRequired:true,
      isDisabled:false,
      employeeList:[],
      canEdit: true,
      audit:false,
      personShow: false,
      personOptions: [],
      doc:{},
      docContinue:{},
      preParams:{},// 上个页面传过来的参数
      beginTime:"",
      // 校验规则
      rules:{
        acceptPerson: [{
          required: true,
          message: '请填写当事人',
          trigger: ['change', 'blur',],
        },],
        validateEnd: [{
          required: true,
          message: '请选择许可证截止日期',
          trigger: ['change', 'blur',],
        },],
        docDate: [{
          required: true,
          message: '请选择承办日期',
          trigger: ['change', 'blur',],
        },],
      },
    };
  }, 
  onLoad() {
    this.preParams = this.getRouteParam();
    certificateService.getDocContinueId(this.preParams.bizUuid).then(uuid => {
      if(uuid.success){
        this.preParams['id'] = uuid.bean;
        this.initDocData();
      }else{
        this.$u.toast(uuid.msg);
      }
    });
    // 查询承办人
    certificateService.choosePersons({checkUuid:this.preParams['bizUuid'],}).then(dr => {
      if (dr.success) {
        let ps = dr.data;
        ps.map(p => {
          p.uid = p.personUuid;
          p.name = p.personName;
          p.exts = [p.leCertNo,];
        });
        this.$nextTick(() => this.personOptions = ps);
      }
    });
  },
  watch: {
    isShowCyBegin(newValue, oldValue) {
      this.$refs.startChangeRef.validation();
    },
    isShowCyEnd(newValue, oldValue) {
      this.$refs.endChangeRef.validation();
    },
  },
  mounted() {
    this.$refs.uForm.setRules(this.rules);
  },
  methods: {
    initDocData(){
      this.getDocStep((res) => {
        let self = this;
        this.$modal.showLoading("数据加载中...");
        certificateService.docContinue(this.preParams).then(conInfo => {
          self.$modal.hideLoading();
          if(conInfo.success){
            let doc = conInfo.data;
            if(doc && doc.length === 2){
              let docRs = doc[1];
              docRs.orgShortName = doc[0].orgShortName;
              docRs.jgsxDealUuid = this.preParams.bizUuid;
              let employeeList = util.parseEmployee(docRs, "inspCardNo", "checkPerson");
              docRs.docDate = !docRs.docDate ? dateUtils.dateFormat("yyyy年MM月dd日",new Date()) : docRs.docDate;

              if ((!docRs.acceptPerson || !docRs.validateEnd) && this.preParams['retailerUuid']) {
                Promise.all([
                  certificateService.getLicInfo({retailerUuid: this.preParams['retailerUuid'],}),
                  certificateService.choosePersons({checkUuid:this.preParams['bizUuid'],}),])
                  .then((ds) => {
                    let [licInfo,personIfno,personNames,certNos,uuids,] = [ds[0].bean,ds[1].data,[],[],[],];
                    !docRs.acceptPerson && (docRs.acceptPerson = licInfo.managerName);
                    !docRs.validateEnd && licInfo.validateEnd && (docRs.validateEnd = dateUtils.dateFormat("yyyy年MM月dd日",new Date(licInfo.validateEnd)));
                    personIfno.forEach(item => {
                      if(item.isChecked){
                        personNames.push(item.personName);
                        certNos.push(item.leCertNo);
                        uuids.push(item.personUuid);
                        employeeList.push({
                          personName:item.personName,
                          leCertNo:item.leCertNo,
                          personUuid:item.personUuid,
                        });
                      }
                    });
                    docRs.checkPerson = personNames.join(",");
                    docRs.inspCardNo = uuids.join(",");
                  });
              }
              this.doc = res;
              this.docContinue = docRs;
              this.$set(this.docContinue,'acceptPerson',docRs.acceptPerson);
              this.employeeList = employeeList;
            }else{
              let employeeList = util.parseEmployee(doc[0], "inspCardNo", "checkPerson");
              this.docContinue = doc[0];
              this.doc = res;
              this.employeeList = employeeList;
            }
          }else{
            this.$u.toast(conInfo.msg);
          }
        });
      });
    },
    // 获取文书状态、阶段
    getDocStep(cb){
      if(this.preParams.id){
        certificateService.getDocIns(this.preParams.id).then(
          (res) => {
            if (res.success) {
              this.canEdit = res.bean.step === 'edit' || res.bean.stepName == '开始';
              this.audit = res.bean.step === '01';
              cb && cb(res.bean);
            }else{
              this.$u.toast(res.msg);
            }
          },
          (err) => {
            this.$u.toast(err);
          }
        );
      }else{
        if(this.preParams.docCode && !this.preParams.docUuid){
          certificateService.getDocConfig({docCode: this.preParams.docCode,}).then(dc => {
            if(dc.success){
              this.preParams['docUuid'] = dc.bean.docUuid;
            }else{
              this.$u.toast(dc.msg);
            }
          });
        }
        this.canEdit = true;
        cb && cb();
      }
    },
    clicDatekHandle(type){
      if(!this.canEdit) return;
      this[type] = true;
    },
    changeDate(type,e){
      this.docContinue[type] = dateUtils.dateFormat("yyyy年MM月dd日",new Date(e.result));
    },
    addTakerUser(type){
      this.personShow = true;
    },
    // 执行人
    handlerSelectPersons(pItems) {
      this.personShow = false;
      this.employeeList = pItems;
    },
    // 提交
    submitAudit(type){
      this.$refs.uForm.validate(valid => {
        if (valid) {
          if(this.employeeList.length == 0) {
            this.$u.toast('请选择承办人');
            return false;
          }
          if(this.employeeList.length < 2) {
            this.$u.toast('承办人至少2人');
            return false;
          }
          if(this.employeeList.length > 2) {
            this.$u.toast('请选择2个承办人');
            return false;
          }
          // 从承办人中组装提交数据
          let personUuids = [];
          let checkPersons = [];
          this.employeeList.forEach(e => {
            personUuids.push(e.personUuid);
            checkPersons.push(e.personName);
          });
          this.docContinue.inspCardNo = personUuids.join(",");
          this.docContinue.checkPerson = checkPersons.join(",");
          let self = this;
          this.$modal.showLoading(`数据${type === "submit" ? '提交' : '保存'}中...`);
          let docUuid = this.preParams.docUuid || this.doc.docUuid;
          certificateService.saveDocContinue(this.docContinue,docUuid).then(res => {
            if (!res.success) {
              this.$modal.hideLoading();
              this.$u.toast(res.msg);
              return;
            }
            if(type === 'submit'){
              let data = res.data[0];
              this.preParams['id'] = res.bean.continueUuid;
              certificateService.submitDocContinue(res.bean,data.docUuid, data.configIns.itemUuid).then(ds => {
                self.$modal.hideLoading();
                if(ds.success){
                  this.$u.toast('提交成功');
                  this.initDocData();
                } else{
                  this.$u.toast(ds.msg);
                }
              });
            }else{
              self.$modal.hideLoading();
              this.$u.toast('保存成功');
            }
          });
        } 
      });
    },
    // 打印
    downloadFile(){
      if (!this.doc.pdfFileId) {
        this.$u.toast("没有文书");
        return;
      }
      this.setRouteParam({fileId:this.doc.pdfFileId,});
      this.$u.route('pages/commonPage/printerComponent');
    },
    /**
	 * @param {Boolean} status 提交还是保存
	 */
    saveBehaviorLog(status, doc){
      commonService.getCurrentTime().then(res2 => {
        let param = {
          bizUuid: doc.bizUuid,
          docUuid:doc.docUuid,
          docInsUuid: doc.docInsUuid, 
          bizType:LOG_STATUS.B007,
          operationType: status == 0 ? LOG_OP_TYPE.saveDoc : LOG_OP_TYPE.submitDoc,
          beginTime: this.beginTime,
          endTime: res2.success ? res2.msg : this.$u.timeFormat(Date.now(), 'yyyy-mm-dd hh:MM:ss'),
          remark: doc.configIns.docName,
        };
        this.beginTime = param.endTime;
        commonService.saveBehaviorLog(param).then(res => {
          console.log(res);
        }).catch(e => {
          console.log(e);
        });
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "style/certificate/common.scss";
.page{
	padding: 0;
}
.desc-btm{
  font-size:13px;
  color: #333;
}
</style>